package com.xb.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.xb.ai.entity.po.User;
import com.xb.ai.mapper.UserMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
@Slf4j
@SuppressWarnings("UnstableApiUsage") // 添加注解以抑制Guava Beta API的警告
public class BloomFilterService {

    private BloomFilter<String> userBloomFilter;

    @Resource
    private UserMapper userMapper;

    // 预计插入数量 (根据你的用户量预估)
    private static final int EXPECTED_INSERTIONS = 10000; 
    // 可接受的误判率 (例如 1%)
    private static final double FPP = 0.01; 

    @PostConstruct
    public void initBloomFilter() {
        log.info("Initializing Bloom Filter for usernames...");
        userBloomFilter = BloomFilter.create(
                Funnels.stringFunnel(StandardCharsets.UTF_8),
                EXPECTED_INSERTIONS,
                FPP
        );

        // 从数据库加载所有用户名到布隆过滤器
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.select(User::getUserAccount);
        List<User> users = userMapper.selectList(userLambdaQueryWrapper);
        if (users != null) {
            for (User user : users) {
                if (user.getUserAccount() != null) {
                    userBloomFilter.put(user.getUserAccount());
                }
            }
        }
    }

    /**
     * 检查用户名是否可能存在于布隆过滤器中
     *
     * @param userAccount 账号
     * @return 如果用户名可能存在则返回 true，否则返回 false
     */
    public boolean mightContain(String userAccount) {
        if (userAccount == null || userBloomFilter == null) { // Add null check for filter
            return false;
        }
        return userBloomFilter.mightContain(userAccount);
    }

    /**
     * 向布隆过滤器中添加一个用户名
     * (用于新用户注册后更新过滤器)
     *
     * @param userAccount 用户账号
     */
    public void put(String userAccount) {
        if (userAccount != null && userBloomFilter != null) { // Add null check for filter
            userBloomFilter.put(userAccount);
            log.info("Added username '{}' to Bloom Filter.", userAccount);
        }
    }
} 